package leetcode.editor.cn;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

//Java：二叉树中和为目标值的路径
public class ErChaShuZhongHeWeiMouYiZhiDeLuJingLcof {
    public static void main(String[] args) {
        Solution solution = new ErChaShuZhongHeWeiMouYiZhiDeLuJingLcof().new Solution();
        // TO TEST
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    class Solution {
        private List<List<Integer>> result = new ArrayList<>();

        public List<List<Integer>> pathTarget(TreeNode root, int target) {
            if (root == null) return result; // 非空判断

            List<Integer> path = new LinkedList<>();
            preorderdfs(root, target, path);
            return result;
        }

        public void preorderdfs(TreeNode root, int targetsum, List<Integer> path) {
            path.add(root.val);
            // 遇到了叶子节点
            if (root.left == null && root.right == null) {
                // 找到了和为 targetsum 的路径
                if (targetsum - root.val == 0) {
                    result.add(new ArrayList<>(path));
                }
                return; // 如果和不为 targetsum，返回
            }

            if (root.left != null) {
                preorderdfs(root.left, targetsum - root.val, path);
                path.remove(path.size() - 1); // 回溯
            }
            if (root.right != null) {
                preorderdfs(root.right, targetsum - root.val, path);
                path.remove(path.size() - 1); // 回溯
            }
        }

    }

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}